package com.blue.gateway.config.filters.decorators;

import com.alibaba.fastjson.JSON;
import com.blue.common.enums.ServiceEnum;
import com.blue.common.exception.JsonResult;
import com.blue.gateway.jwt.JwtTokenUtil;
import com.blue.user.model.entity.SysLoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 登陆成功后的修饰处理
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
public class LoginSucceedRespDecorator extends ServerHttpResponseDecorator {

    private ServerHttpResponse originalResponse;
    private Integer scope;

    public LoginSucceedRespDecorator(ServerHttpResponse originalResponse, Integer scope) {
        super(originalResponse);
        this.originalResponse = originalResponse;
        this.scope = scope;
    }

    @Override
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        if (body instanceof Flux) {
            Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
            return super.writeWith(fluxBody.map(dataBuffer -> {
                // probably should reuse buffers
                byte[] content = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(content);
                // 释放掉内存
                DataBufferUtils.release(dataBuffer);
                String responseString = new String(content, StandardCharsets.UTF_8);
                JSON responseJson = (JSON) JSON.parse(responseString);
                log.info("登录相应解析信息：{}", responseJson.toJSONString());
                content = rewriteResult(responseJson);
                // TODO，responseJson就是response的值，想修改、查看就随意而为了
                byte[] uppedContent = new String(content, StandardCharsets.UTF_8).getBytes();
                return bufferFactory.wrap(uppedContent);
            }));
        }
        return super.writeWith(body);
    }

    /**
     * 获得返回的字节数组
     */
    private byte[] rewriteResult(JSON parse) {
        JsonResult result = JSON.toJavaObject(parse, JsonResult.class);
        if (result.isOk() && null != result.getData()) {
            if (ServiceEnum.CLIENT.getCode().equals(Integer.valueOf(this.scope))) {
                SysLoginUserInfo data = JSON.parseObject(JSON.toJSONString(result.getData()), SysLoginUserInfo.class);
                // 子类实现
                String token = JwtTokenUtil.generateToken(data);
                log.info("用户登录系统,生成Token值：{}", token);
                // TODO 随意对返回数据做修改，比如过滤敏感信息等,以及具体的授权菜单信息
                data.setToken(token);
                result.setData(data);
            }
        }
        String nullResp = JSON.toJSONString(result);
        return nullResp.getBytes();
    }
}
